<template>
  <!-- 注册界面 -->
  <div class="register-form">
    <el-input v-model.trim="query.username" placeholder="请输入手机号"></el-input>
    <el-input v-model.trim="query.password" placeholder="请输入密码" type="password"></el-input>
    <el-input v-model.trim="query.re_password" placeholder="请再次输入密码" type="password"></el-input>

    <!-- 验证码 输入和获取 -->
    <div class="captcha">
      <el-input v-model.trim="query.code" placeholder="请输入验证码"></el-input>
      <el-button type="primary" @click="getCaptcha" :disabled="captchaCooldown">
        {{ captchaCooldown ? '请稍后再试' : '获取验证码' }}
      </el-button>
    </div>

    <!-- 按钮组 -->
    <div class="btn">
      <el-button type="primary" @click="register">注册</el-button>
      <el-button type="primary" @click="router.push('/login')">返回登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import router from '../router/index.js';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const query = ref({
  username: '',
  password: '',
  re_password: '',
  code: ''
});

const captchaCooldown = ref(false);

const handleError = (message, error) => {
  ElMessage.error(message);
  console.error(error);
};

const handleSuccess = (message, data) => {
  ElMessage.success(message);
  console.log(data);
};

const getCaptcha = () => {
  if (captchaCooldown.value) {
    return;
  }
  if (!query.value.username) {
    handleError('请输入用户名');
    return;
  }
  captchaCooldown.value = true;
  axios.get(`http://localhost:8000/app/sms/${query.value.username}`)
    .then(res => {
      handleSuccess('验证码已发送', res.data);
    })
    .catch(error => {
      handleError('验证码发送失败', error);
    })
    .finally(() => {
      setTimeout(() => {
        captchaCooldown.value = false;
      }, 60000); // 1分钟冷却时间
    });
};

const register = () => {
  if (!query.value.username) {
    handleError('请输入用户名');
    return;
  }
  if (!query.value.password || !query.value.re_password) {
    handleError('请输入密码');
    return;
  }
  if (query.value.password !== query.value.re_password) {
    handleError('两次输入的密码不一致');
    return;
  }
  axios.post(`http://localhost:8000/app/create/`, query.value)
    .then(res => {
      handleSuccess('注册成功', res.data);
      router.push('/login');
    })
    .catch(error => {
      handleError('注册失败', error);
    });
};

onMounted(() => {
  captchaCooldown.value = false;
});
</script>

<style scoped>
.register-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.captcha {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.el-input {
  margin-bottom: 10px;
  width: 100%;
}
</style>
